#include "stdafx.h"

/* Maintain sorted and unsorted array, 
   Find the minimum element from unsorted array and grow the sorted array
*/

void SelectionSort(long arr[], long n)
{
    // While growing the sorted array
    // Iterated in the unsorted array to find min value and its position
    // Swap it with the end of sorted array.
    for(int sortedPos = 0; sortedPos < n; ++sortedPos)
    {
        long minValue = arr[sortedPos], minIndex = sortedPos;
        for(int ind = sortedPos; ind < n; ++ind)
        {
            if(arr[ind] < minValue)
            {
                minValue = arr[ind];
                minIndex = ind;
            }
        }
        long temp = arr[sortedPos];
        arr[sortedPos] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    long arr[] = {64, 25, 12, 22, 11};
    long n = sizeof(arr)/sizeof(arr[0]);

    SelectionSort(arr, n);

    printf("Sorted array: \n");
    for (int ind = 0; ind < n; ind++)
        printf("%d ", arr[ind]);
    printf("\n");

    getchar();
    return 0;
	
}